/**
 * author : Rahul.Mittal@in.ibm.com
 *
 * This file depends upon prototype.js and scriptaculous.js framework for AJAX and animation.
 *
 * Initial version was given by frog for RSS, but lot of modifications have been done 
 *     to this file to make it work in the portal environment .
 *
 * Please look at the documentation of prototype and scriptaculous for more information.
 *
 * For View Mode :
 * 1. Fetch the RSS content from the provider.<b> 
 * 2. Construct a RSS2.0 object.<b> 
 * 3. Apply the style to the Object.<b> 
 * 4. Apply the listeners and animation on the title and description.
 *
 * For Edit Mode:
 * 1.Register the listeners on the links.<b> 
 * 2.Provide the animation effect.
 *
 */


     /**
     * to check the browser.
     */
    IB=function(){
	    var agt=navigator.userAgent.toLowerCase();
	    
	    this.is_major=parseInt(navigator.appVersion);
        this.is_minor=parseFloat(navigator.appVersion);
        
	    this.is_ie=((agt.indexOf("msie") != -1) && (agt.indexOf("opera") == -1));
	    this.is_ie3    = (this.is_ie && (this.is_major < 4));
	    this.is_ie4    = (this.is_ie && (this.is_major == 4) && (agt.indexOf("msie 4")!=-1) );
	    this.is_ie4up  = (this.is_ie && (this.is_major >= 4));
	    this.is_ie5    = (this.is_ie && (this.is_major == 4) && (agt.indexOf("msie 5.0")!=-1) );
	    this.is_ie5_5  = (this.is_ie && (this.is_major == 4) && (agt.indexOf("msie 5.5") !=-1));
	    this.is_ie5up  = (this.is_ie && !this.is_ie3 && !this.is_ie4);
	    this.is_ie5_5up =(this.is_ie && !this.is_ie3 && !this.is_ie4 && !this.is_ie5);
	    this.is_ie6    = (this.is_ie && (this.is_major == 4) && (agt.indexOf("msie 6.")!=-1) );
	    this.is_ie6up  = (this.is_ie && !this.is_ie3 && !this.is_ie4 && !this.is_ie5 && !this.is_ie5_5  && !this.is_ie6); // true if the browser is greater that IE6.
    }

 
	/*
	 * Open the link in a new browser window.
	 */
	function openWindow(url){
        window.open(url,'_blank');
    }
   
    function adjustGadgetHeight(){
		// Tells gadget to resize itself
		gadgets.window.adjustHeight();
	}
    /**
     * This class defines the behaviour of the feeds.
     */    
	xohmRSSPortlet = function() {
		this.portlet = $('xRSSPortletDisp');
		//alert("this.portlet :" + this.portlet);
		this.feed = this.portlet.down('.xRSSContent');
		this.items = new Array();
		this.activeEffect = null;
		
//		var els = this.feed.getElementsByClassName('xRSSItem');
		// fixed for safari.. 
		var els = this.feed.select('.xRSSItem');
		els.each(function(e){this.items.push(new xohmRSSItem(e, els));}.bind(this));
		//truncateDesc($(els[0]).down('.xRSSDescription'), 0, 297, false);
		
		$(els[0]).down('.xRSSTitle').removeClassName('xCollapsed');
		var ib = new IB(); 
		if(ib.is_ie6){// Fix for IE-6 browsers.
			$(els[0]).down('.xRSSDescription').setStyle({position:'fixed'}).show();
		}else{
			$(els[0]).down('.xRSSDescription').show();
		}
		setTimeout("adjustGadgetHeight()", 500);
	}

	
	/**
	 * class defined for Feed Item.
	 *
	 */
	xohmRSSItem = function(el, els) {
		
		this.item = $(el);
		this.title = this.item.down('.xRSSTitle');
		this.description = this.item.down('.xRSSDescription');
		this.activeEffect = null;
		
		this.description.setStyle({position:'relative',top:'auto',left:'auto'}).hide();
		this.title.setStyle({cursor:'pointer'}).observe('click',function(e){this.toggleItem(e, els);}.bind(this)).addClassName('xCollapsed');
		this.title.down('a').observe('click',function(e){e.stop();});
	}
	
	/**
	 * toggle the feed description using the script-aculo-us js api.
	 */
	xohmRSSItem.prototype.toggleItem = function(e, els) {
		if (e) e.stop();
		if (this.activeEffect != null) this.activeEffect.cancel();
		//truncateDesc(this.description, 0, 297, false);
		for(var i=0; i<els.length; i++){
			if($(els[i]) == this.item){
				if( $(els[i]).down('.xRSSTitle').className == 'xRSSTitle'){// if open
					
					//this.activeEffect = new Effect.BlindUp(this.description, {duration:0.5});
					this.description.hide();

					this.title.addClassName('xCollapsed');
				}else{ // if close
					this.title.removeClassName('xCollapsed');
					
					//this.activeEffect = new Effect.BlindDown(this.description, {duration:0.5});
					this.description.show();

				}
			}else{
				if($(els[i]).down('.xRSSTitle').className == 'xRSSTitle'){
					
					//this.activeEffect = new Effect.BlindUp($(els[i]).down('.xRSSDescription'), {duration:0.5});
					$(els[i]).down('.xRSSDescription').hide();

					$(els[i]).down('.xRSSTitle').addClassName('xCollapsed');
				}
			}
		}
		// Tells gadget to resize itself
		gadgets.window.adjustHeight();

	}


	/**
	 * TODO : pass the no of entries as a parameter
	 */
  	function getRssContentFromGoogle(result){
  		if (!result.error){
			var _xmlRef = result.xmlDocument;
			//alert("_xmlRef :" + _xmlRef) ;
			processRSS(_xmlRef, 10, null, false);
		}else{
			  $("xRSSContent").hide();
			  $("xRSSContentError").show();
		}
  	}



  	/* Process the feeds fetched from the Feed provider.*/
  	function processRSS(rssxml, noOfItems, proxy, dispTitle){
		RSS = new RSS2Channel(rssxml, noOfItems);
		showRSS(RSS, proxy, dispTitle);
	}
  	
	//object containing the parsed RSS 2.0 channel
	function RSS2Channel(rssxml, noOfItems){
		//required
		this.title;
		this.link;
		this.description;
		this.url;
	
		//array of RSS2Item objects
		this.items = new Array();
	
		var chanElement = rssxml.getElementsByTagName("channel")[0];	
		var itemElements = rssxml.getElementsByTagName("item");	
		itemElements = eval(itemElements);
		// set the noOfItems to display here.
		var _itemNo = (noOfItems<=itemElements.length)?noOfItems:itemElements.length;
		
		for (var i=0; i < _itemNo; i++){
		    var Item;
		    try{
			Item = new RSS2Item(eval(itemElements[i]));
			}catch(error){ // If any error occurs, leave the feed and continue.
				continue;
			}
			this.items.push(Item);
		}
		var properties = new Array("title", "link", "description","url");
		var tmpElement = null;
		for (var i=0; i<properties.length; i++)	{
			tmpElement = chanElement.getElementsByTagName(properties[i])[0];
			if (tmpElement!= null){
				eval("this."+properties[i]+"=tmpElement.childNodes[0].nodeValue");
			}	
		}
	}  	
	
	//object containing the RSS 2.0 item
	function RSS2Item(itemxml){
		//required
		this.title;
		this.link;
		this.description;
		var properties = new Array("title", "link", "description");
        try{ //for safety kept it in a try-catch. 
			var tmpElement = null;
			for (var i=0; i<properties.length; i++)	{
				tmpElement = itemxml.getElementsByTagName(properties[i])[0];
				var tempTextVal = "";
				if(tmpElement != null && tmpElement.childNodes.length >0){
					for(var len=0 ; len<tmpElement.childNodes.length; len++){
						tempTextVal += tmpElement.childNodes[len].nodeValue;
					}
				}
				eval("this."+properties[i]+"=tempTextVal");
			}
		}catch(err){
		    throw "ParsingError";
		}
	}
	
	//shows the RSS content in the browser. Tags are constucted according to the Frog reference code.
	function showRSS(RSS, dispTitle){
	 	var _rssContentId = "xRSSContent";
 		var _target = $(_rssContentId);
 		items_html = "";
 			//items_html = "<h5>"+ RSS.title + "</h5>";
			if(RSS.url == null || RSS.url == 'undefined'){
 				items_html  +="<a href=\""+ RSS.link +"\" target=\"_blank\" rel=\"nofollow\"  title=\"" + "Go to " + RSS.title + "\">"
 			                + RSS.title + "</a>" 
 			                + "<p class=\"xRssTitleDesc\">" +RSS.description + "</p>" + "<hr>" ;
			}else{
 				items_html  +="<a href=\""+ RSS.link +"\" target=\"_blank\" rel=\"nofollow\"  title=\"" + "Go to " + RSS.title + "\">"
 			                +"<img src=\"" + RSS.url + "\" border=\"0\" " + ">" + "</a>" 
 			                + "<br/>"+ "<p class=\"xRssTitleDesc\">" +RSS.description + "</p>" + "<hr>" ;
			}
 			//alert("RSS.link :" + RSS.link + "  RSS.desc :" + RSS.description);
		items_html += "<ul>";
		for (var i=0; i<RSS.items.length; i++){
		      item_start_html = '<li class="xRSSItem">';
		      title_start_html = '<h2 class="xRSSTitle">';
		      if(RSS.items[0].link != ""){
		      	  title_text_html = "<a href=\"#\" onclick=\"openWindow('"+ RSS.items[i].link+"');\">" + RSS.items[i].title + "</a>";	
		      }else{
		      	  title_text_html = RSS.items[i].title ;	
		      }
		      title_end_html = '</h2>';
		      desc_start_html = '<div class="xRSSDescription">';
		      desc_text_html = '<p>' + RSS.items[i].description + '<\p>';
		      desc_end_html = '</div>';
			  item_end_html = '</li>';
			  
			  items_html += item_start_html + title_start_html + title_text_html + title_end_html 
			  				+ desc_start_html + desc_text_html + desc_end_html + item_end_html;
		}	
		items_html += "</ul>";
		_target.innerHTML  = items_html;	 
		 
	    new xohmRSSPortlet();// give animation effects.
		
		return true;
	}